package com.study.spark.scala.nginx.dao

import java.sql.{Connection, PreparedStatement}

import com.study.spark.scala.nginx.`case`.UrlTopNStat
import com.study.spark.scala.nginx.util.MySQLUtils

import scala.collection.mutable.ListBuffer

/**
  * 各个维度统计的DAO操作
  *
  * @author: stephen.shen
  * @create: 2019-03-18 14:09
  */
object StatDAO {

  /**
    * 批量保存insertDayUrlAccessTopN到数据库
    */
  def insertDayUrlAccessTopN(list: ListBuffer[UrlTopNStat]): Unit = {

    var connection: Connection = null
    var pstmt: PreparedStatement = null

    try {
      connection = MySQLUtils.getConnection()

      connection.setAutoCommit(false) //设置手动提交

      val sql = "insert into day_url_access_topn(date,url,times) values (?,?,?) "
      pstmt = connection.prepareStatement(sql)

      for (ele <- list) {
        pstmt.setString(1, ele.date)
        pstmt.setString(2, ele.url)
        pstmt.setLong(3, ele.times)

        pstmt.addBatch()
      }

      pstmt.executeBatch() // 执行批量处理
      connection.commit() //手工提交
    } catch {
      case e: Exception => e.printStackTrace()
    } finally {
      MySQLUtils.release(connection, pstmt)
    }
  }

}
